import React, { Component } from 'react';
import { Form, Icon, Input, Button, message } from 'antd';
import router from 'umi/router';
import styles from './Login.less';
import { connect } from 'dva';

@connect(({ account }) => ({
  account,
}))
class LoginForm extends Component {
  constructor(props) {
    super(props);
  }

  login = () => {
    const { dispatch, form } = this.props;

    form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'account/login',
          payload: { acc: values.account, pwd: values.password },
          callback: response => {
            if (response.ErrorMessage) {
              message.error(response.ErrorMessage+'，账号密码有误');
            }
          },
        });
      } else {
        message.error('账号或密码不能为空!');
      }
    });
  };

  handleEnterKey = e => {
    if (e.keyCode === 13) {
      this.login();
    }
  };

  componentDidMount() {
    //组件挂载时候，注册keypress事件
    document.addEventListener('keypress', this.handleEnterKey);
  }
  componentWillUmount() {
    //组件卸载时候，注销keypress事件
    document.removeEventListener('keypress', this.handleEenterKey);
  }

  render() {
    const { getFieldDecorator } = this.props.form;

    return (
      <div className={styles.bg}>
        <div className={styles.loginPanel}>
          <Form className={styles.loginForm}>
            <Form.Item>
              {getFieldDecorator('account', {
                initialValue: '',
                rules: [{ required: true, message: '请输入用户名' }],
              })(
                <Input
                  prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  placeholder="请输入用户名"
                />
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码' }],
              })(
                <Input
                  prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  type="password"
                  placeholder="请输入密码"
                />
              )}
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                onClick={this.login.bind(this)}
                className={styles.loginFormButton}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

const Login = Form.create()(LoginForm);
export default Login;
